import React, { useState, useCallback } from "react";
import { Form, Input, Button, Checkbox, message } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import { loginAPI, getRoutersAPI } from "@/api/user.js";
import useAuthStore from "@/store/authStore.js";
import "./index.scss";

// 提取常量
const FORM_RULES = {
  username: [
    { required: true, message: "请输入用户名!" },
    { min: 3, message: "用户名至少3个字符" },
  ],
  password: [
    { required: true, message: "请输入密码!" },
    { min: 6, message: "密码至少6个字符" },
  ],
};

const Login = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const setAuth = useAuthStore((state) => state.setAuth);
  const setMenus = useAuthStore((state) => state.setMenus);

  // 使用useCallback优化性能
  const handleFinish = useCallback(
    async (values) => {
      if (loading) return;
      try {
        setLoading(true);

        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 10000);

        const { username, password } = values;
        if (!username?.trim() || !password?.trim()) {
          message.error("用户名或密码不能为空");
          return;
        }

        // 先登录
        const loginResponse = await loginAPI(values, {
          signal: controller.signal,
        }).catch((error) => {
          if (error.name === "AbortError") {
            message.error("登录请求超时，请重试");
          }
          return { code: 500 };
        });

        if (loginResponse.code !== 200) {
          message.error(loginResponse.msg || "登录失败，请重试");
          return;
        }

        const { token, userInfo } = loginResponse.data;
        setAuth(token, userInfo);

        // 再获取菜单
        const routersResponse = await getRoutersAPI({
          signal: controller.signal,
        }).catch(() => ({
          code: 500,
        }));

        clearTimeout(timeoutId);

        if (routersResponse.code === 200) {
          setMenus(routersResponse.data);
        } else {
          message.warning("获取菜单失败，部分功能可能受限");
        }
        message.success("登录成功");
        navigate("/", { replace: true });
      } catch (error) {
        console.error("登录错误:", error);
        message.error("登录过程中出现错误，请重试");
      } finally {
        setLoading(false);
      }
    },
    [loading, navigate, setAuth, setMenus]
  );

  const handleForgotPassword = useCallback(() => {
    // 处理忘记密码逻辑
    message.info("忘记密码功能开发中");
  }, []);

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 relative">
      <div className="absolute bottom-0 z-0 h-[550px] w-full p-[10px] overflow-hidden">
        <div className="ocean">
          <div className="wave"></div>
          <div className="wave"></div>
        </div>
      </div>

      <div className="relative z-10 bg-white p-8 rounded-lg shadow-xl w-full max-w-md mx-[10px]">
        <div className="text-center">
          <h2 className="text-3xl font-bold text-gray-900">登录系统</h2>
          <p className="mt-2 text-sm text-gray-600">请输入您的账号和密码</p>
        </div>

        <Form
          form={form}
          name="loginForm"
          onFinish={handleFinish}
          className="mt-8 space-y-6"
          initialValues={{ remember: true }}
        >
          <Form.Item name="username" rules={FORM_RULES.username}>
            <Input
              prefix={<UserOutlined className="text-gray-400" />}
              size="large"
              placeholder="用户名"
              autoComplete="username"
            />
          </Form.Item>

          <Form.Item name="password" rules={FORM_RULES.password}>
            <Input.Password
              prefix={<LockOutlined className="text-gray-400" />}
              size="large"
              placeholder="密码"
              autoComplete="current-password"
            />
          </Form.Item>

          <div className="flex items-center justify-between">
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>记住我</Checkbox>
            </Form.Item>
            <div
              className="text-sm text-blue-600 hover:text-blue-800 cursor-pointer"
              onClick={handleForgotPassword}
            >
              忘记密码？
            </div>
          </div>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              className="w-full"
              size="large"
              loading={loading}
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
